package com.liting.uitest.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.liting.uitest.entity.FileInfo;
import com.liting.uitest.model.BaseRes;
import com.liting.uitest.service.FileInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


@RestController
@Slf4j
@Api(tags = "文件管理")
public class FileController {
    @Autowired
    private FileInfoService fileInfoService;

    @PostMapping(value = "image/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @ApiOperation("图片上传")
    public BaseRes<FileInfo> uploadFile(@RequestPart("file") MultipartFile image, @RequestPart("metadata") String metadata) {
        try {
            BaseRes<FileInfo> result = fileInfoService.uploadFile(image);
            return result;
        } catch (Exception ex) {
            log.error("uploadFile error", ex);
            return new BaseRes<>(null, 1, "上传文件失败");

        }
    }

    @GetMapping("image/list")
    @ApiOperation("图片查询")
    public BaseRes<?> getFileList(
            @RequestParam(required = false) Integer pageNum,
            @RequestParam(required = false) Integer pageSize,
            @RequestParam(required = false) String fileName,
            @RequestParam(required = false) String uploadDate
    ) {
        try {
            if (pageNum == null) pageNum = 1;
            if (pageSize == null) pageSize = 5;

            Page<FileInfo> fileList = fileInfoService.getFileList(pageNum, pageSize, fileName, uploadDate);
            return new BaseRes<>(fileList);
        } catch (Exception ex) {
            log.error("getFileList error", ex);
            return new BaseRes<>(null, 1, "查询文件列表失败");
        }
    }

    @GetMapping("/image/info")
    @ApiOperation("图片详情")
    public BaseRes<FileInfo> getFile(@RequestParam("id") Long id) {
        try {
            FileInfo fileInfo = fileInfoService.getFile(id);
            return new BaseRes<>(fileInfo);
        } catch (Exception ex) {
            log.error("getFile error", ex);
            return new BaseRes<>(null, 1, "获取文件失败");
        }
    }


}
